<template>
  <div id="indexView">
    <Header />
    <div class="main">
      <!-- <div class="mapBox" id="mapBox">
        <MapContainer></MapContainer>
      </div> -->
      <div class="contentBox flexbox justifyBetween alignStretch">
        <div class="left">
          <div class="siderItemBox flexbox flexcolumn alignStretch">
            <div class="siderItemHead">充电设备状态</div>
            <div class="siderItemBody">
              <StatusChart :chartData="equipmentStatusCountData" />
            </div>
          </div>
          <div class="siderItemBox flexbox flexcolumn alignStretch">
            <div class="siderItemHead">设备实时报警</div>
            <div class="siderItemBody">
              <AlarmChart :chartData="realTimeWarningCountData" />
            </div>
          </div>
          <div class="siderItemBox flexbox flexcolumn alignStretch">
            <div class="siderItemHead">场站排名</div>
            <div class="siderItemBody">
              <Rank :list="stationRank" />
            </div>
          </div>
        </div>

        <div class="center">
          <div class="centerTop">
            <PanelGroup :chartData="panelGroupData" />
            <div class="mapBox2" id="mapBox2">
              <MapContainer :stationData="mapResData" />
            </div>
          </div>
          <div class="siderItemBox flexbox flexcolumn alignStretch">
            <div class="siderItemHead">充电设备趋势</div>
            <div class="siderItemBody">
              <TrendChart :chartData="equipmentEarningTrendData" />
            </div>
          </div>
        </div>

        <div class="right flexcolumn">
          <div class="siderItemBox flexbox flexcolumn alignStretch">
            <div class="siderItemHead">用户数据统计</div>
            <div class="siderItemBody">
              <UserStatistics :chartData="userGroupData" />
            </div>
          </div>
          <div class="siderItemBox flexbox flexcolumn alignStretch">
            <div class="siderItemHead">宣传视频</div>
            <div class="siderItemBody" style="padding: 0">
              <video
                class="propagateVideo"
                autoplay
                loop
                muted
                src="http://47.99.114.111/static/media/WeChat_20240919102859.f1f89b18.mp4"
              ></video>
            </div>
          </div>
          <div class="siderItemBox flexbox flexcolumn alignStretch">
            <div class="siderItemHead">设备排名</div>
            <div class="siderItemBody">
              <Rank :list="deviceRank" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import autofit from 'autofit.js'
import Header from '@/components/Header.vue'
import MapContainer from '@/components/MapContainer.vue'
import { wsManager } from '@/utils/websocket/ws-manager'
import { WS_MESSAGE_TYPES } from '@/utils/websocket/ws-types'

import StatusChart from './dashboard2/StatusChart.vue'
import AlarmChart from './dashboard2/AlarmChart.vue'
import TrendChart from './dashboard2/TrendChart.vue'
import UserStatistics from './dashboard2/UserStatistics.vue'
import Rank from './dashboard2/Rank.vue'
import Rank2 from './dashboard2/Rank2.vue'
import PanelGroup from './dashboard2/PanelGroup.vue'
// import PeriodChart from './dashboard2/PeriodChart.vue'

import {
  equipmentStatusCount,
  realTimeWarningCount,
  stationEarningCount,
  equipmentEarningCount,
  userCount,
  indexCount,
  equipmentEarningTrend,
  getMapData
} from '@/api/chart'

defineOptions({
  name: 'Index'
})

console.log(wsManager)

// 总量统计数据
const panelGroupData = ref({})
// 用户数据统计
const userGroupData = ref({})
// 场站排名数据
const stationRank = ref([])
// 设备排名数据
const deviceRank = ref([])
// 设备状态统计数据
const equipmentStatusCountData = ref([])
// 设备报警统计数据
const realTimeWarningCountData = ref([])
// 设备收益趋势统计数据
const equipmentEarningTrendData = ref({})
// 地图数据
const mapResData = ref([])

const unsubscribes = ref([])

// 注册数据更新处理器
const registerHandlers = () => {
  const handlers = {
    [WS_MESSAGE_TYPES.equipmentStatus]: getEquipmentStatusCountData,
    [WS_MESSAGE_TYPES.realTimeWarning]: getRealTimeWarningCountData,
    [WS_MESSAGE_TYPES.stationEarning]: getStationEarningCountData,
    [WS_MESSAGE_TYPES.equipmentEarning]: getEquipmentEarningCountData,
    [WS_MESSAGE_TYPES.userCount]: getUserCountData,
    [WS_MESSAGE_TYPES.indexCount]: getIndexCountData,
    [WS_MESSAGE_TYPES.equipmentTrend]: () => getEquipmentEarningTrendData(1, 1),
    [WS_MESSAGE_TYPES.mapData]: getMapResData,
    [WS_MESSAGE_TYPES.all]: refreshAllData
  }

  // 订阅所有消息类型
  Object.entries(handlers).forEach(([type, handler]) => {
    const unsubscribe = wsManager.getService()?.subscribe(type, handler)
    if (unsubscribe) {
      unsubscribes.value.push(unsubscribe)
    }
  })
}

// 获取设备状态统计
const getEquipmentStatusCountData = async () => {
  const res = await equipmentStatusCount({ stationIds: [] })

  const tempMap = {
    chargingCount: '放电中',
    dischargingCount: '补电',
    idleCount: '空闲',
    offlineCount: '离线',
    faultCount: '报警'
  }
  let tempArr = []

  Object.keys(res).forEach((key) => {
    if (key != 'totalCount') {
      tempArr.push({
        name: tempMap[key],
        value: res[key],

        key: key
      })
    }
  })

  equipmentStatusCountData.value = tempArr
}

// 获取实时告警统计
const getRealTimeWarningCountData = async () => {
  const res = await realTimeWarningCount({ stationIds: [] })

  const tempMap = {
    faultCount1: '一级预警',
    faultCount2: '二级预警',
    faultCount3: '三级预警'
  }
  let tempArr = []

  Object.keys(res).forEach((key) => {
    if (key != 'total') {
      tempArr.push({
        name: tempMap[key],
        // value: res[key],
        // 模拟假数据
        value: Math.ceil(Math.random() * 100),
        key: key
      })
    }
  })

  // tempArr.total = res.total
  tempArr.total = tempArr.reduce((a, b) => {
    return a + b.value
  }, 0)

  realTimeWarningCountData.value = tempArr
}

// 获取场站收益排名
const getStationEarningCountData = async () => {
  const res = await stationEarningCount({ queryRange: 4, limit: 8, stationIds: [] })
  // 模拟假数据
  // const res2 = Array.from({ length: 10 }, (item, index) => {
  //   return {
  //     id: index,
  //     name: `设备${index}`,
  //     value: Math.ceil(Math.random() * 100)
  //   }
  // })

  res.forEach((item) => {
    item.id = item.stationId
    item.name = item.stationName
    item.value = item.earning
  })
  stationRank.value = res
}

// 获取设备收益排名
const getEquipmentEarningCountData = async () => {
  const res = await equipmentEarningCount({ queryRange: 4, limit: 8, stationIds: [] })
  // 模拟假数据
  // const res2 = Array.from({ length: 10 }, (item, index) => {
  //   return {
  //     id: index,
  //     name: `设备${index}`,
  //     value: Math.ceil(Math.random() * 100)
  //   }
  // })

  res.forEach((item) => {
    item.id = item.stationId
    item.name = item.equipmentName
    item.value = item.earning
  })
  deviceRank.value = res
}

// 获取用户数据统计
const getUserCountData = async () => {
  // const res = await userCount({ queryRange: 4 })
  const res = await userCount()
  userGroupData.value = res
}

// 获取首页总数量统计
const getIndexCountData = async () => {
  const res = await indexCount({ stationIds: [] })
  panelGroupData.value = res
}

// 获取设备收益趋势
const getEquipmentEarningTrendData = async (time, type) => {
  const res = await equipmentEarningTrend({ stationIds: [], queryType: type, queryRange: time })

  equipmentEarningTrendData.value = res
}

// 获取地图数据
const getMapResData = async () => {
  const res = await getMapData()

  mapResData.value = res
}

// 全量更新数据
const refreshAllData = async () => {
  try {
    await Promise.all([
      getEquipmentStatusCountData(),
      getRealTimeWarningCountData(),
      getStationEarningCountData(),
      getEquipmentEarningCountData(),
      getUserCountData(),
      getIndexCountData(),
      getEquipmentEarningTrendData(1, 1),
      getMapResData()
    ])
    console.log('全量数据更新完成')
  } catch (error) {
    console.error('全量数据更新失败:', error)
  }
}

// autofit 实例
let autofitInstance = null

onMounted(() => {
  // 初始化 WebSocket 服务
  wsManager.initService({
    // url: import.meta.env.VITE_WS_URL
    url: `ws://${location.hostname}:8881/admin/websocket/bigScreen`
    // url: `ws://192.168.1.199:8881/admin/websocket/bigScreen`
    // url: import.meta.env.VITE_WS_URL || 'ws://192.168.1.198:8881/admin/websocket/bigScreen'
    // url: '/websocket'
  })

  // 注册消息处理器
  registerHandlers()

  // 初始化数据
  refreshAllData()

  // 只有在 scale 模式下才初始化 autofit
  if (import.meta.env.VITE_ADAPT_MODE === 'scale') {
    autofitInstance = autofit.init(
      {
        dw: 3840,
        dh: 2160
        // el: '#app',
        // mode: 'scale'
        // cssMode: 'scale'
        // ignore: ['#mapBox2']
        // ignore: ['.echarts-tooltip']
        // ignore: [
        //   {
        //     el: '#mapContainer',
        //     width: '100%',
        //     height: '100%',
        //     fontSize: '100px',
        //     scale: 1
        //   }
        // ]
      },
      false
    )
  }

  // getEquipmentStatusCountData()
  // getRealTimeWarningCountData()
  // getStationEarningCountData()
  // getEquipmentEarningCountData()
  // getUserCountData()
  // getIndexCountData()

  // getEquipmentEarningTrendData(1, 1)

  // getMapResData()
})

onBeforeUnmount(() => {
  // 取消所有订阅
  unsubscribes.value.forEach((unsubscribe) => unsubscribe())
})
</script>

<style>
#indexView {
  width: 100%;
  height: 100%;
  margin: 0 auto;
}

.main {
  box-sizing: border-box;
  flex: 1;
  width: 100%;
  height: 100%;
  padding: 200px 0 40px;
  isolation: isolate;
}
.mapBox {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
  pointer-events: auto;
  background-color: rgba(173, 25, 25, 0.1);
}
.contentBox {
  flex: 1;
  z-index: 2;
  height: 100%;
  pointer-events: none;
}
.left,
.right {
  gap: 40px;
  width: 25%;
  height: 100%;
  display: grid;

  grid-template-rows: repeat(3, 1fr);
  pointer-events: auto;
}
.center {
  overflow: hidden;
  pointer-events: auto;
  display: grid;
  width: 50%;
  margin: 40px 40px 0;
  grid-template-rows: 2fr 1fr;
  gap: 40px;
}
.centerTop {
  overflow: hidden;
  display: grid;
  grid-template-rows: 240px 1fr;
  gap: 40px;
}
.mapBox2 {
  overflow: hidden;
  width: 100%;
}
.siderItemBox {
  overflow: hidden;
  /* width: 100%;
  height: 100%; */
  /* flex: 1; */

  /* background-color: rgba(255, 255, 255, 0.1); */
}
.siderItemHead {
  position: relative;
  box-sizing: border-box;
  flex-shrink: 0;
  height: 60px;
  padding: 0 60px;
  /* padding: 5px 35px; */
  /* background: url('@/assets/imgs/siderHeaderBg.png') left top/cover no-repeat; */
  background: linear-gradient(to right, rgba(0, 107, 94, 0.5), rgba(0, 141, 123, 0.1));
  border-top: 4px solid #31db85;
  font-size: 32px;
  line-height: 60px;
  color: #fff;
}
.siderItemHead::before,
.siderItemHead::after {
  content: '';
  position: absolute;
  top: 22px;
  width: 16px;
  height: 16px;
  background-color: #31db85;
}
.siderItemHead::before {
  left: 22px;
}
.siderItemHead::after {
  right: 22px;
}
.siderItemBody {
  overflow: hidden;
  flex: 1 1 0;
  padding: 30px;
  background-color: rgba(0, 0, 0, 0.4);
  color: #fff;
}
.propagateVideo {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
